package com.cqie.rbac.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cqie.rbac.entity.SysMenu;
import com.cqie.rbac.vo.MenuRoleVo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 菜单实体 Mapper 接口
 * </p>
 *
 * @author 夏兵
 * @since 2021-09-02
 */
@Mapper
public interface SysMenuMapper extends BaseMapper<SysMenu> {

    /**
     * 查询角色id对应的菜单id
     *
     * @param id 角色id
     * @return 菜单数组
     */
    @Select("SELECT\n" +
            "\tsr.id,\n" +
            "\tsr.`name`,\n" +
            "\tsr.`status`,\n" +
            "\tGROUP_CONCAT( rm.menu_id ) menus \n" +
            "FROM\n" +
            "\tsys_role sr\n" +
            "\tLEFT JOIN role_menu rm ON sr.id = rm.role_id \n" +
            "WHERE\n" +
            "\tsr.id = ${id}")
    MenuRoleVo getRoleMenu(@Param("id") Long id);

    /**
     * 删除菜单以及他的所有子节点
     *
     * @param delId 需要删除菜单的id
     * @return 影响条数
     */
    @Delete("DELETE FROM sys_menu sm WHERE sm.id = ${id} OR sm.parentId = ${id}")
    int delMenuAndSon(@Param("id") Long delId);

    /**
     * 查询现有子菜单中最大的序号
     *
     * @param parentId 父节点id
     * @return 最大序号
     */
    @Select("SELECT\n" +
            "\tMax( sm.sortCode ) maxCode \n" +
            "FROM\n" +
            "\tsys_menu sm \n" +
            "WHERE\n" +
            "\tsm.parentId = ${parentId}")
    Integer sonMenuMaxCode(@Param("parentId") Long parentId);

    /**
     * 查出用户对应的子菜单
     * @param uId 用户id
     * @return 子菜单集合
     */
    @Select("SELECT DISTINCT\n" +
            "\tsm.id,\n" +
            "\tsm.`name`,\n" +
            "\tsm.appUrl,\n" +
            "\tsm.imgUrl,\n" +
            "\tsm.sortCode,\n" +
            "\tsm.parentId \n" +
            "FROM\n" +
            "\tsys_user su\n" +
            "\tLEFT JOIN user_role ur ON su.id = ur.user_id\n" +
            "\tLEFT JOIN sys_role sr ON ur.role_id = sr.id\n" +
            "\tLEFT JOIN role_menu rm ON ur.role_id = rm.role_id\n" +
            "\tJOIN sys_menu sm ON rm.menu_id = sm.id \n" +
            "WHERE\n" +
            "\tsu.id = ${uId} \n" +
            "\tAND sr.`status` = 0 \n" +
            "\tAND sm.menu_type = '按钮'"
    )
    List<SysMenu> queryUserMenu(@Param("uId") Long uId);
}
